<?php

namespace App\Http\Controllers\AdminApi\User;

use App\Http\Controllers\Controller;
use App\Http\Models\Admin\ModelHasRoles;
use App\Http\Models\Admin\Role_;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash as FacadesHash;
use PhpParser\Node\Expr\Empty_;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Contracts\Role;

class UserController extends Controller
{
    //修改登录用户信息
    public function updateMessage(Request $request)
    {
        $info = $request->get('userInfo');
        $id = $info['id'];
        $name = $info['name'];
        $username = $info['username'];
        $oldPwd = $info['oldPwd'];
        $pwd = $info['pwd'];
        $preg_name = '/^[\x{4e00}-\x{9fa5}]{2,4}+$/u'; //正则验证中文姓名
        $preg_nickName = '/^[a-z]{4,12}+$/i'; //正则验证英文姓名
        $preg_pwd = '/^[a-zA-Z0-9_\\@\\#\\$\\%\\^\\&\\*\\(\\)\\!\\,\\.\\?\\-\\+\\|\\=]{6,16}$/'; //验证密码
        $result = User::where('id', $id)->first();
        $flag =  FacadesHash::check($oldPwd, $result->password); //验证旧密码是否相等
        $flagOld =  FacadesHash::check($pwd, $result->password); //验证新密码是否和旧密码相等
        // if (!preg_match($preg_name, $name) && !preg_match($preg_nickName, $name)) {
        //     return response()->json(['code' => 20001, 'message' => '请输入正确的姓名!2-4位中文或4-12位英文!', 'data' => null]);
        // }
        if (mb_strlen($username, 'UTF-8') > 15) {
            return response()->json(['code' => 20001, 'message' => '用户名最大15位,请重新输入!', 'data' => null]);
        }
        if (!$flag) {
            return response()->json(['code' => 20001, 'message' => '旧密码输入错误,请重新输入!', 'data' => null]);
        }
        if (mb_strlen($pwd, 'UTF-8') < 6) {
            return response()->json(['code' => 20001, 'message' => '新密码不合法最少6位,请重新输入!', 'data' => null]);
        }
        if ($flagOld) {
            return response()->json(['code' => 20001, 'message' => '新密码与旧密码相同,请重新输入!', 'data' => null]);
        }
        if (!preg_match($preg_pwd, $pwd)) {
            return response()->json(['code' => 20001, 'message' => '新密码不合法,不能含有中文!', 'data' => null]);
        }
        //修改密码前需要对密码进行加密处理
        $password = FacadesHash::make($pwd);
        $arr = [
            'name' => $name,
            'username' => $username,
            'password' => $password
        ];
        $res = User::where('id', $id)->update($arr);
        return response()->json(['code' => 20000, 'message' => '修改信息成功!', 'data' => null]);
    }

    // //获取员工信息
    // public function getStaff()
    // {
    // }

    //获取全部人员信息
    public function getAllUser()
    {
        $uid = Auth::guard('adminapi')->user()->id;
        $user = User::where(array('id' => $uid))->first();
        $userRolesId = $user->roles()->pluck('id')->toArray(0)[0];
        $role = Role_::find($userRolesId);

        $users = User::select('*');
        if ($role->name != 'administrator') {
            $users->whereHas('hasManyrole', function ($q) {
                $q->where('name', '!=', 'administrator');
            });
        }
        $users->with(['hasManyrole']);
        $users = $users->paginate(15);


        return response()->json(['code' => 20000, 'message' => '人员查询成功', 'data' => $users]);
    }

    //查询已有角色
    public function getRoles()
    {
        $roles = Role_::all();
        return response()->json(['code' => 20000, 'message' => '角色查询成功', 'data' => $roles]);
    }

    //添加人员并分配角色
    public function insertUser(Request $request)
    {
        $userInfo = $request->get('userInfo');
        $name = $userInfo['name'];
        // dd($name);die;
        $username = $userInfo['username'];
        $password = $userInfo['password'];
        $arrRoles = $userInfo['role'];
        // dd($arrRoles);die;
        $preg_name = '/^[\x{4e00}-\x{9fa5}]{2,18}+$/u'; //正则验证中文姓名
        $preg_nickName = '/^[a-z]{4,12}+$/i'; //正则验证英文姓名
        $preg_email = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/'; //正则验证邮箱
        // $arrRoles = [];
        // for ($i = 0; $i < sizeof($roless); $i++) {
        //     array_push($arrRoles, $roless[$i]['name']);
        // }
        if (empty($name)) {
            return response()->json(['code' => 20001, 'message' => '请输入姓名!', 'data' => null]);
        }
        if (empty($username)) {
            return response()->json(['code' => 20001, 'message' => '请输入用户名!', 'data' => null]);
        }
        if (empty($password)) {
            return response()->json(['code' => 20001, 'message' => '请输入密码!', 'data' => null]);
        }
        // if (!preg_match($preg_name, $name) && !preg_match($preg_nickName, $name)) {
        //     return response()->json(['code' => 20001, 'message' => '请输入正确的姓名!2-18位中文或4-12位英文!', 'data' => null]);
        // }
        if (mb_strlen($username, 'UTF-8') > 15) {
            return response()->json(['code' => 20001, 'message' => '用户名不合法,最大15位!', 'data' => null]);
        }
        // echo strlen($password);die;
        if (mb_strlen($password, 'UTF-8') < 6) {
            return response()->json(['code' => 20001, 'message' => '密码长度过短,最少6位!', 'data' => null]);
        }
        if (empty($password)) {
            return response()->json(['code' => 20001, 'message' => '请输入密码!', 'data' => null]);
        }
        //判断当前输入的用户名是否已经存在
        $resEmail = User::where('username', $username)->first();
        if (!empty($resEmail)) {
            return response()->json(['code' => 20001, 'message' => '用户名已存在,请重新输入!', 'data' => null]);
        }
        if (empty($arrRoles)) {
            return response()->json(['code' => 20001, 'message' => '请分配角色!', 'data' => null]);
        }
        // dd($arrRoles);die;
        $user = new User();


        $user->name = $name;
        $user->username = $username;
        $user->password = $password;
        $user->is_clerk = "0";
        $user->roles = "admin@admin.com";

        $user->save();
        //添加角色
        $user->assignRole($arrRoles);
        return response()->json(['code' => 20000, 'message' => '人员信息添加成功!', 'data' => null]);
    }

    //修改管理员信息
    public function updateUser(Request $request)
    {
        // die;
        $id = $request->get('id');
        $userInfo = $request->get('userInfo');
        $name = $userInfo['name'];
        $password = $userInfo['password'];
        $confirmPassword = $userInfo['confirmPassword'];
        $arrRoles = [
            'role' => $userInfo['role']
        ];
        // dd($userInfo['role']);die;
        $preg_name = '/^[\x{4e00}-\x{9fa5}]{2,4}+$/u'; //正则验证中文姓名
        $preg_nickName = '/^[a-z]{4,12}+$/i'; //正则验证英文姓名
        // $preg_email = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/'; //正则验证邮箱
        if (empty($name)) {
            return response()->json(['code' => 20001, 'message' => '请输入姓名!', 'data' => null]);
        }
        $user = User::findOrFail($id); //当前id 人员的信息
        // var_dump($user->password);
        // die;
        if (!empty($password)) {
            if (!empty($confirmPassword)) {
                //两次密码不为空的情况下
                if ($password != $confirmPassword) {
                    return response()->json(['code' => 20001, 'message' => '两次密码不一致,请重新输入!', 'data' => null]);
                }
            } else {
                return response()->json(['code' => 20001, 'message' => '请输入确认密码!', 'data' => null]);
            }
            // die;
            //密码加密
            $pwd = FacadesHash::make($password);
        } else {
            if (!empty($confirmPassword)) {
                return response()->json(['code' => 20001, 'message' => '两次密码不一致,请重新输入!', 'data' => null]);
            }
            $pwd = $user->password;
        }

        // if (!preg_match($preg_name, $name) && !preg_match($preg_nickName, $name)) {
        //     return response()->json(['code' => 20001, 'message' => '请输入正确的姓名!2-4位中文或4-12位英文!', 'data' => null]);
        // }


        //判断当前输入的姓名是否已经存在
        $resName = User::where('name', $name)->first(); //当前输入邮箱查询 是否存在数据
        //判断当前输入的姓名是否存在数据库 排除当前人员未修改前的姓名
        if ($user->name !== $name) {
            if (!empty($resName)) {
                return response()->json(['code' => 20001, 'message' => '当前输入的姓名已存在!', 'data' => null]);
            }
        }
        //当修改人员信息时，当他是科员修改为其他角色时，查询分公司账号信息 是否归当前科员所属，如果有删除
        $result = User::where('is_clerk', '2')->get();
        for ($i = 0; $i < sizeof($result); $i++) {
            if ($result[$i]->clerk != null) {
                $arr = explode(',', $result[$i]->clerk);
                for ($j = 0; $j < sizeof($arr); $j++) {
                    if ($arr[$j] == $name) {
                        array_splice($arr, $j, 1);
                        $str = implode(',', $arr);
                        $arrays = [
                            'clerk' => $str
                        ];
                        $userId = $result[$i]->id;
                        $res =   User::where('id', $userId)->update($arrays);
                        // dd($res);
                        // die;
                    }
                }
            }
        }
        //修改角色后无论修改成什么都应该将clerk 分公司所属清空
        if ($userInfo['role'] == "科员") {
            //当将科员角色修改后 应将这个人员管理的分公司 信息删除
            $array = [
                'name' => $name,
                'is_clerk' => "1",
                'clerk' => null,
                'password' => $pwd
            ];
        } else if ($userInfo['role'] == "分公司账号") {

            $array = [
                'name' => $name,
                'is_clerk' => "2",
                'clerk' => null,
                'password' => $pwd
            ];
        } else {
            $array = [
                'name' => $name,
                'is_clerk' => "0",
                'clerk' => null,
                'password' => $pwd
            ];
        }
        // dd($array);die;
        User::where('id', $id)->update($array);
        // $user->update($array);
        $user->syncRoles($arrRoles);
        return response()->json(['code' => 20000, 'message' => '管理员信息修改成功!', 'data' => null]);
    }

    //删除管理员
    public function deleteUser(Request $request)
    {
        $id  = $request->get('id');
        $user = User::findOrFail($id);
        $user->delete();
        $models = new ModelHasRoles();
        $model = ModelHasRoles::where('model_id', '=', $id)->delete();
        // dd($model);die;
        return response()->json(['code' => 20000, 'message' => '删除信息成功!', 'data' => $id]);
    }
}
